package com.smartian.v2.utils;

import android.text.TextUtils;

import com.smartian.v2.Constants;
import com.smartian.v2.OpLog;
import com.smartian.v2.TextPattern;
import com.smartian.v2.model.DateTimeNode;
import com.smartian.v2.model.ScheduleTaskBean;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by tianweitong on 2020/4/1.
 */

public class DateTimeResultFilter {

   static final SimpleDateFormat sOuputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    /**
     * 获取最接近的时间段
     * @param scheduleTask
     * @return
     */
    public static String getClosestDateTime(ScheduleTaskBean scheduleTask) {

        if(scheduleTask==null ) return null;
        String dateTime = scheduleTask.getDateTime();
        String dateformat = scheduleTask.getDateTimeFormat();
        int repeatType = scheduleTask.getRepeatType();

        long baseDateTime = getBaseDateTime(dateTime, dateformat);
        Calendar baseCalendar = Calendar.getInstance();
        baseCalendar.setTimeInMillis(baseDateTime);

        int YEAR = baseCalendar.get(Calendar.YEAR);
        int MONTH = baseCalendar.get(Calendar.MONTH) + 1;
        int DAY = baseCalendar.get(Calendar.DAY_OF_MONTH);

        int HOUR = baseCalendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = baseCalendar.get(Calendar.MINUTE);

        int DAY_OF_WEEK = baseCalendar.get(Calendar.DAY_OF_WEEK);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND,0);
        calendar.set(Calendar.SECOND,0);

        long currentTimes = calendar.getTimeInMillis();

        long timeInMillis = 0l;

        switch (repeatType){
                case TextPattern.REPEAT_EVERY_DAY:
                    calendar.set(Calendar.HOUR_OF_DAY,HOUR);
                    calendar.set(Calendar.MINUTE,MINUTE);
                    timeInMillis = calendar.getTimeInMillis();
                    while ((timeInMillis<currentTimes)){
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        timeInMillis = calendar.getTimeInMillis();
                    }
                    break;
                case TextPattern.REPEAT_EVERY_WORK_DAY:
                    calendar.set(Calendar.HOUR_OF_DAY,HOUR);
                    calendar.set(Calendar.MINUTE,HOUR);
                    timeInMillis = calendar.getTimeInMillis();
                    while ((timeInMillis<currentTimes) || !isWorkDay(calendar)){
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        timeInMillis = calendar.getTimeInMillis();
                    }

                    break;
                case TextPattern.REPEAT_WEELY:
                    calendar.set(Calendar.DAY_OF_WEEK,DAY_OF_WEEK);
                    calendar.set(Calendar.HOUR_OF_DAY,HOUR);
                    calendar.set(Calendar.MINUTE,MINUTE);
                    timeInMillis = calendar.getTimeInMillis();
                    while ((timeInMillis<currentTimes)){
                        calendar.add(Calendar.DAY_OF_MONTH,7);
                        timeInMillis = calendar.getTimeInMillis();
                    }
                    break;
                case TextPattern.REPEAT_MONTHLY:
                    int M = calendar.get(Calendar.MONTH) + 1;
                    int Y = calendar.get(Calendar.YEAR);
                    int TD = calendar.get(Calendar.DAY_OF_MONTH);

                    if(TD<DAY) {
                        if (DAY < 29) {
                            calendar.set(Calendar.DAY_OF_MONTH, DAY);
                        } else if (M == 2 && DAY == 29) {
                            if (!DateTimeHelper.isLeapYear(Y)) {
                                calendar.add(Calendar.MONTH, 1);
                            }
                            calendar.set(Calendar.DAY_OF_MONTH, DAY);
                        } else if (DAY >= 29 && DAY <= 30) {
                            calendar.set(Calendar.DAY_OF_MONTH, DAY);
                        } else {
                            if (!DateTimeHelper.has31Day(M)) {
                                int next31DayMonth = DateTimeHelper.getNext31DayMonth(M);
                                if (next31DayMonth < M) {
                                    calendar.add(Calendar.YEAR, 1);
                                }
                                calendar.set(Calendar.MONTH, next31DayMonth - 1);
                            }
                            calendar.set(Calendar.DAY_OF_MONTH, DAY);

                        }
                    }else if(TD>DAY){
                        if ((M + 1) == 2) {
                            if (DateTimeHelper.isLeapYear(calendar.get(Calendar.YEAR))) {
                                if (DAY <= 29) {
                                    calendar.add(Calendar.MONTH, 1);
                                    calendar.set(Calendar.DAY_OF_MONTH, DAY);
                                } else {
                                    calendar.add(Calendar.MONTH, 2);
                                    calendar.set(Calendar.DAY_OF_MONTH, DAY);
                                }
                            } else if (DAY < 28) {
                                calendar.add(Calendar.MONTH, 1);
                                calendar.set(Calendar.DAY_OF_MONTH, DAY);
                            } else {
                                calendar.add(Calendar.MONTH, 2);
                                calendar.set(Calendar.DAY_OF_MONTH, DAY);
                            }
                        } else {
                            calendar.add(Calendar.MONTH, 1);
                            calendar.set(Calendar.DAY_OF_MONTH, DAY);
                        }
                    }
                    calendar.set(Calendar.HOUR_OF_DAY, HOUR);
                    calendar.set(Calendar.MINUTE, MINUTE);
                    break;
                case TextPattern.REPEAT_YEARLY:

                    calendar.set(Calendar.YEAR,YEAR);
                    calendar.set(Calendar.DAY_OF_MONTH,DAY);
                    calendar.set(Calendar.MONTH,MONTH-1);
                    calendar.set(Calendar.HOUR_OF_DAY, HOUR);
                    calendar.set(Calendar.MINUTE, MINUTE);

                    timeInMillis = calendar.getTimeInMillis();
                    while ((timeInMillis<currentTimes)){
                        calendar.add(Calendar.YEAR,1);
                        timeInMillis = calendar.getTimeInMillis();
                    }
                    break;
                case TextPattern.REPEAT_NONE:
                    calendar.setTimeInMillis(baseDateTime);
                    break;
                default:
                    break;
        }

        OpLog.d("AsrReminder",""+OpLog.formatTime(calendar.getTimeInMillis()));
        return sOuputSDF.format(calendar.getTimeInMillis());
    }

    private static long getBaseDateTime(String dateTime, String dateformat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
        try {
            Date date = sdf.parse(dateTime);
            if(date!=null){
                return date.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0l;
    }

    public static boolean isWorkDay(Calendar calendar) {

//        if(HolidayApiService.isAvailable()){
//            return HolidayApiService.checkIsWorkDay(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DAY_OF_MONTH));
//        }
        return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
                || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY;
    }


    public static int getScheduleTaskRepeatType(ScheduleTaskBean scheduleTask) {
        if(scheduleTask==null) return -1;
        int fraquent = scheduleTask.getFraquent();
        switch (scheduleTask.getRepeatType()){
            case TextPattern.REPEAT_EVERY_DAY:
                return Constants.REPEAT_EVERY_DAY;
            case TextPattern.REPEAT_EVERY_WORK_DAY:
                return Constants.REPEAT_EVERY_WORKING_DAY;
            case TextPattern.REPEAT_WEELY:

                if(fraquent==1){
                    return Constants.REPEAT_WEEKLY;
                }else if(fraquent==2){
                    return Constants.REPEAT_EVERY_TWO_WEEKS;
                }
                break;
            case TextPattern.REPEAT_MONTHLY:
                if(fraquent==1){
                    return Constants.REPEAT_PER_MONTH;
                }else if(fraquent==3){
                    return Constants.REPEAT_EVERY_THREE_MONTHS;
                }else if(fraquent==6){
                    return Constants.REPEAT_EVERY_SIX_MONTHS;
                }

                break;
            case TextPattern.REPEAT_YEARLY:
                if(fraquent==1) {
                    return Constants.REPEAT_PER_YEAR;
                }
                break;
            case TextPattern.REPEAT_NONE:
                return Constants.REPEAT_NONE;
        }

        return -1;
    }

    public static String findSubject(String source, ScheduleTaskBean scheduleTask) {
        if(TextUtils.isEmpty(source)){
            return "有一个定时任务";
        }

        String subjectTitle = findSubjectTitleAsCategory(source);
        if(!TextUtils.isEmpty(subjectTitle)){
            return subjectTitle;
        }
        subjectTitle = parseSubjectTitleWithDateTimeNodes(source, scheduleTask, subjectTitle);

        if(TextUtils.isEmpty(subjectTitle)){
            subjectTitle =  "有一个定时任务";
        }
        return subjectTitle;

    }

    private static String parseSubjectTitleWithDateTimeNodes(String sourceText, ScheduleTaskBean scheduleTask, String subjectTitle) {
        if(scheduleTask!=null && !TextUtils.isEmpty(sourceText)) {

            String repeatText = scheduleTask.getRepeatText();
            List<DateTimeNode> dateTimeNodes = scheduleTask.getDateTimeNodes();

            String titleText  = sourceText;
            if(!TextUtils.isEmpty(repeatText)){
                titleText = titleText.replaceAll(repeatText,"");
            }

            if(dateTimeNodes!=null) {

                for (int j = 0; j < dateTimeNodes.size(); j++) {
                    DateTimeNode dateTimeNode = dateTimeNodes.get(j);
                    if (dateTimeNode == null) continue;
                    String text = dateTimeNode.text;
                    String locatorText = dateTimeNode.locatorText;

                    if (!TextUtils.isEmpty(text)) {
                        titleText = titleText.replaceAll(text, "");
                    }
                    if (!TextUtils.isEmpty(locatorText)) {
                        titleText = titleText.replaceAll(locatorText, "");
                    }
                }
            }
            String[] stringParts = titleText.split("[，。,. ？? 、]");
            for (int i = 0; i < stringParts.length; i++) {
                String  partString = stringParts[i];
                if (!TextUtils.isEmpty(partString)) {
                    subjectTitle = partString;
                    break;
                }
            }
        }

        if(TextUtils.isEmpty(subjectTitle)){
            subjectTitle = sourceText;
        }
        if(!TextUtils.isEmpty(subjectTitle)){
            subjectTitle = subjectTitle.replaceAll(WordConstant.REMINDER_ME,"").replaceAll(WordConstant.REMEBER,"");
        }
        if (TextUtils.isEmpty(subjectTitle)){
            subjectTitle = sourceText;
            subjectTitle = subjectTitle.replaceAll(WordConstant.REMINDER_ME,"").replaceAll(WordConstant.REMEBER,"");
        }

        if(TextUtils.equals(WordConstant.REMINDER_KEYWORD,subjectTitle)){
            subjectTitle = "";
        }

        return subjectTitle;
    }

    private static String findSubjectTitleAsCategory(String sourceText) {
        if(TextUtils.isEmpty(sourceText)) return sourceText;
        for(int i = 0; i< WordConstant.TITLE_CATEGORIES.length; i++){
            String category = WordConstant.TITLE_CATEGORIES[i];
            if(sourceText.contains(category)){
                category = category.replaceAll(WordConstant.REMINDER_ME,"").replaceAll(WordConstant.REMEBER,"");
                return category;
            }
        }

        for (int i = 0; i< WordConstant.TITLE_PATTERNS_COMPLEX_ME_2.length; i++){
            Matcher matcher = Pattern.compile(WordConstant.TITLE_PATTERNS_COMPLEX_ME_2[i]).matcher(sourceText);
            if(matcher.find()){
                String group = matcher.group();
                if(group.length()>5){
                    return group.substring(5);
                }
            }
        }

        for (int i = 0; i< WordConstant.TITLE_PATTERNS_COMPLEX_ME_1.length; i++){
            Matcher matcher = Pattern.compile(WordConstant.TITLE_PATTERNS_COMPLEX_ME_1[i]).matcher(sourceText);
            if(matcher.find()){
                String group = matcher.group();
                if(group.length()>2){
                    String title = group.substring(2);
                    if(!WordConstant.REMINDER_ME.equals(title)){
                        return title;
                    }
                }
            }
        }

        for (int i = 0; i< WordConstant.TITLE_PATTERNS_ME.length; i++){
            Matcher matcher = Pattern.compile(WordConstant.TITLE_PATTERNS_ME[i]).matcher(sourceText);
            if(matcher.find()){
                String group = matcher.group();
                if(group.length()>3){
                    String title = group.substring(3);
                    if(!WordConstant.REMEBER.equals(title)){
                        return title;
                    }
                }
            }
        }

        for (int i = 0; i< WordConstant.TITLE_PATTERNS.length; i++){
            Matcher matcher = Pattern.compile(WordConstant.TITLE_PATTERNS[i]).matcher(sourceText);
            if(matcher.find()){
                String group = matcher.group();
                group = group.replaceAll(WordConstant.REMINDER_ME,"").replaceAll(WordConstant.REMEBER,"");
                return group;
            }
        }
        return null;
    }
}
